<?php

namespace app\admin\service;

use app\admin\validate\LabelValidate;
use support\spark\exception\ApiException;
use support\spark\model\user\UserLabel;

class LabelService
{
    /**
     * 获取标签列表
     * @param $param
     * @return array
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $where = [];

        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        $labelModel = new UserLabel();
        $list=$labelModel->getPaginateList($where, ['*'], ['id' => 'desc'], [], $limit);

        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加标签
     * @param $param
     * @return array
     */
    public function addLabel($param)
    {
        // 检验完整性
        $validate = new LabelValidate();
        if (!$validate->scene('edit')->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $labelModel = new UserLabel();
        $has = $labelModel->checkUnique([
            'name' => $param['name']
        ]);
        if (!empty($has)) {
            throw  new  ApiException('该标签已经存在', -2);
        }
        $param['create_time'] = now();
        $param['update_time'] = now();
        $labelModel->insertOne($param);
        return  dataReturn(0,'添加成功');
    }

    /**
     * 编辑标签
     * @param $param
     * @return array
     */
    public function editLabel($param)
    {
        // 检验完整性
        $validate = new LabelValidate();
        if (!$validate->scene('edit')->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $labelModel = new UserLabel();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['name', '=', $param['name']];
        $has = $labelModel->checkUnique($where);
        if (!empty($has)) {
            throw  new  ApiException('该标签已经存在', -2);
        }
        $labelModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }
}